﻿using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using ShopGrpcService.Models;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace ShopGrpcService.Services
{
    public class ProductService : Product.ProductBase

    {
        private ShopContext shopdb;
        private ILogger<ProductService> logger;

        public ProductService(ShopContext shopContext, ILogger<ProductService> log)
        {
            shopdb = shopContext;
            logger = log;
        }

        public override Task<ProductListResponse> GetProductList(Empty request, ServerCallContext context)
        {
            var res = new ProductListResponse();
            var prolist = shopdb.Products.Select(p => new ProductInfo
            {
                ProductId = p.ProductId,
                ProductName = p.ProductName,
                ProductPrice = Convert.ToDouble(p.ProductPrice),
                ProductStock = Convert.ToInt32(p.Stock),
                ProductDesc = p.ProductDesc
            }).ToArray();
            logger.LogInformation($"以读取到商品数据:{prolist.Length}条");
            //foreach (var item in prolist)
            //{
            //    res.ProductInfos.Add(item);
            //}
            res.ProductInfos.Add(prolist);
            return Task.FromResult(res);
        }
    }
}